[C#] GrayScale (by ColorMatrix) causes OutOfMemoryException. Why ?

Posted by Tony on Stack Overflow See other posts from Stack Overflow or by Tony
Published on 2009-05-29T11:30:36Z Indexed on 2010/03/30 4:03 UTC
Read the original article Hit count: 466

Filed under:
|

I have 2 forms, A and B. On the Form A, I click a button and an Image is being loaded to a PictureBox located ona the Form B. And, I want to set GrayScale to this image by:

   public void SetGrayScale(PictureBox pb)
    {
        ColorMatrix matrix = new ColorMatrix(new float[][]
        {
            new float[] {0.299f, 0.299f, 0.299f, 0, 0},
            new float[] {0.587f, 0.587f, 0.587f, 0, 0},
            new float[] {0.114f, 0.114f, 0.114f, 0, 0},
            new float[] {     0,      0,      0, 1, 0},
            new float[] {     0,      0,      0, 0, 0}
        });

        Image image = (Bitmap)pb.Image.Clone();

        ImageAttributes attributes = new ImageAttributes();
        attributes.SetColorMatrix(matrix);

        Graphics graphics = Graphics.FromImage(image);

        graphics.DrawImage(image,
                            new Rectangle(0, 0, image.Width, image.Height),
                            0,
                            0,
                            image.Width,
                            image.Height,
                            GraphicsUnit.Pixel,
                            attributes);

        graphics.Dispose();

        pb.Image = image;
    }

This code works properly when the PictureBox is on the same form (A). But, when it is on the Form B, the OutOfMemoryException is raised. Why ?

© Stack Overflow or respective owner

Related posts about c#

Related posts about grayscale